﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Text.RegularExpressions;
using System.IO;

namespace CsWpfImp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }
        List<ChData> ChDataList
        {
            get
            {
                return (List<ChData>)InfoGrid.ItemsSource;
            }
            set
            {
                InfoGrid.ItemsSource = value;
            }
        }
        private void btSelFolderClick(object sender, RoutedEventArgs e)
        {
            var dialog = new System.Windows.Forms.FolderBrowserDialog();
            dialog.Description = "请选择文件路径";
            var result = dialog.ShowDialog();
            if (result == System.Windows.Forms.DialogResult.OK)
            {
                lbSelFolder.Content = dialog.SelectedPath;
            }
        }

        private void btLoadClick(object sender, RoutedEventArgs e)
        {
            int ch = check_channel(tbChannelSel.Text);
            string folder = lbSelFolder.Content.ToString();
            if (ch < 0)
            {
                MessageBox.Show($"通道错误！！！");
                return;
            }
            if (folder == "" || folder == "无")
            {
                MessageBox.Show($"请先选择文件夹！！！");
                return;
            }
            ChDataList = null;
            string filter_name = "*_ch" + ch.ToString() + ".bin";
            string[] files = Directory.GetFiles(folder,
                            filter_name, SearchOption.AllDirectories);
            if (files == null || files.Length == 0)
            {
                MessageBox.Show($"没有找到数据文件！！！");
                return;
            }
            Array.Sort(files);
            List<ChData> info_list = new List<ChData>();
            uint index = 0;
            foreach (var file in files)
            {
                using (FileStream fs = System.IO.File.OpenRead(file))
                {
                    byte[] b = new byte[78];
                    while (true)
                    {
                        int ret = fs.Read(b, 0, b.Length);
                        if (ret == b.Length)
                        {
                            ChRawData raw = new ChRawData(b);
                            ChData conv = new ChData();
                            DateTime startTime =
                                TimeZone.CurrentTimeZone.ToLocalTime(
                                    new DateTime(1970, 1, 1));
                            DateTime now_time = startTime.AddSeconds(raw.timestamp_s);
                            conv.Index = ++index;
                            conv.TimeStamp = now_time.ToString();
                            conv.StepIndex = raw.step_index;
                            conv.RunTime = raw.run_time;
                            conv.Status = raw.status; ;
                            conv.Mode = raw.mode;
                            conv.Flag = raw.flag;
                            conv.Voltage = raw.voltage;
                            conv.Current = raw.current;
                            conv.Capacity = raw.capacity;
                            conv.Power = raw.power;
                            conv.BatTemp = raw.bat_temp;
                            info_list.Add(conv);
                        }
                        else if (ret > 0)
                        {
                            MessageBox.Show("警告：数据文件有错误！！！\n" + file);
                        }
                        else
                        {
                            break;
                        }
                    }

                }
            }
            ChDataList = info_list;
        }
        static int check_channel(string channel_text)
        {
            string pattern = @"^\s*([0-9]+)\s*$";
            var matches = Regex.Matches(channel_text, pattern);
            if (matches.Count == 1)
            {
                return int.Parse(matches[0].Groups[1].Value);
            }
            return -1;
        }

        private void btExportClick(object sender, RoutedEventArgs e)
        {
            if (ChDataList == null || ChDataList.Count == 0)
            {
                MessageBox.Show("没有可导出的数据！！！");
                return;
            }

            System.Windows.Forms.SaveFileDialog dialog = 
                                new System.Windows.Forms.SaveFileDialog()
            {
                DefaultExt = "csv",
                Filter = "CSV Files (*.csv)|*.csv",
                FilterIndex = 1
            };


            if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                string strFormat = dialog.FileName;
                string fomart = "{0},{1},{2},{3},{4},{5},{6},{7},{8},{9},{10},{11}\n";
                string content =
                    "序号," +
                    "时间戳," +
                    "工步号," +
                    "运行时间," +
                    "状态," +
                    "模式," +
                    "Flag," +
                    "电压," +
                    "电流," +
                    "容量," +
                    "能量," +
                    "电池温度\n";
                int write_linex = 0;
                foreach ( var info in ChDataList)
                {
                    content += String.Format(fomart,
                                    info.Index,
                                    info.TimeStamp,
                                    info.StepIndex,
                                    info.RunTime,
                                    info.Status,
                                    info.Mode,
                                    info.Flag,
                                    info.Voltage,
                                    info.Current,
                                    info.Capacity,
                                    info.Power,
                                    info.BatTemp);
                    ++ write_linex;
                    if (write_linex >= 128)
                    {
                        File.AppendAllText(strFormat, content, UnicodeEncoding.UTF8);
                        write_linex = 0;
                        content = null;
                    }
                }
                if (content != null)
                {
                    File.AppendAllText(strFormat, content, UnicodeEncoding.UTF8);
                }
                MessageBox.Show("导出成功");
            }
        }
    }
    public class ChData
    {
        public uint Index { get; set; }
        public string TimeStamp { get; set; }
        public uint StepIndex { get; set; }
        public uint RunTime { get; set; }
        public uint Status { get; set; }
        public uint Mode { get; set; }
        public uint Flag { get; set; }
        public float Voltage { get; set; }
        public float Current { get; set; }
        public float Capacity { get; set; }
        public float Power { get; set; }
        public float BatTemp { get; set; }
    }
    public class ChRawData
    {
        public uint timestamp_s;
        public uint timestamp_us;
        public ushort step_index;
        public ushort process_cycle;
        public ushort step_cycle;
        public uint run_time;
        public byte status;
        public byte mode;
        public byte flag;
        public byte ign_status;
        public float voltage;
        public float current;
        public float capacity;
        public float power;
        public float bat_temp;
        public float dcr;
        public float probe_voltage;
        public float dcir;
        public float line_voltage;
        public float reserve0;
        public float reserve1;
        public float reserve2;
        public float reserve3;
        public float reserve4;

        public ChRawData(byte[] datas)
        {
            MemoryStream ms = new MemoryStream(datas, 0, datas.Length);
            BinaryReader br = new BinaryReader(ms);
            timestamp_s = br.ReadUInt32();
            timestamp_us = br.ReadUInt32();
            step_index = br.ReadUInt16();
            process_cycle = br.ReadUInt16();
            step_cycle = br.ReadUInt16();
            run_time = br.ReadUInt32();
            status = br.ReadByte();
            mode = br.ReadByte();
            flag = br.ReadByte();
            ign_status = br.ReadByte();
            voltage = br.ReadSingle();
            current = br.ReadSingle();
            capacity = br.ReadSingle();
            power = br.ReadSingle();
            bat_temp = br.ReadSingle();
            dcr = br.ReadSingle();
            probe_voltage = br.ReadSingle();
            dcir = br.ReadSingle();
            line_voltage = br.ReadSingle();
            reserve0 = br.ReadSingle();
            reserve1 = br.ReadSingle();
            reserve2 = br.ReadSingle();
            reserve3 = br.ReadSingle();
            reserve4 = br.ReadSingle();
        }
    }

}
